package com.niit.agricstore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.niit.agricstore.entity.Address;
import com.niit.agricstore.mapper.AddressMapper;
import com.niit.agricstore.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper,Address> implements AddressService {

    @Autowired
     AddressMapper addressMapper;

    @Override
    public void addAddress(Address address) {
        addressMapper.insert(address);
    }
    @Override
    public void updateAddress(Address address) {
        addressMapper.updateById(address);
    }

    @Override
    public void deleteAddress(int addressId) {
        addressMapper.deleteById(addressId);
    }

    @Override
    public List<Address> getAddressListByUserId(long userId) {
        QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return addressMapper.selectList(queryWrapper);
    }

    @Override
    public Address getDefaultAddressByUserId(long userId) {
        QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .eq("is_default", true);
        return addressMapper.selectOne(queryWrapper);
    }

    @Override
    public Address getAddressById(int addressId) {
        return addressMapper.selectById(addressId);
    }

    @Override
    public List<Address> searchAddressByKeyword(String keyword) {
        QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("address", keyword);
        return addressMapper.selectList(queryWrapper);
    }


    @Override
    public void setDefaultAddress(long userId, int addressId) {
        // 先将该用户的其他地址设为非默认
        UpdateWrapper<Address> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("is_default",1)
                .eq("user_id", userId);
        addressMapper.update(null, updateWrapper);

        // 再将指定地址设为默认

    }
}
